package com.itrident;

import com.intellij.ide.fileTemplates.impl.UrlUtil;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.itrident.data.Path;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author cxx
 * @create 2020-11-30 21:28
 **/
public class TemplateUtil {

    private static final Configuration configuration = new Configuration(Configuration.VERSION_2_3_28);

    public static void handler(List<Path> paths, VirtualFile virtualFile, String realPath, String packagePath){
        try {
            for (Path path : paths) {
                String templateStr = UrlUtil.loadText (TemplateUtil.class.getResource (path.getPre ()+path.getPath ()));
                StringTemplateLoader stringTemplateLoader=new StringTemplateLoader();
                int end = path.getPath ().lastIndexOf (".");
                String name = path.getPath ().substring (0,end+1)+path.getType ();
                stringTemplateLoader.putTemplate("temp",templateStr);
                configuration.setTemplateLoader(stringTemplateLoader);
                Template template = configuration.getTemplate ("temp");
                File file = createFile(realPath,name);
                Map<String, String> param = new HashMap<> ();
                param.put ("packagePath",packagePath);
                process(template,file,param);
            }
        } catch (IOException e) {

        }finally {
            VfsUtil.markDirtyAndRefresh (true,true,true,virtualFile);
        }
    }

    private static File createFile(String realPath, String name) {
        File file = new File (realPath + name);
        File parentFile = file.getParentFile ();
        if (!parentFile.exists ()) {
            parentFile.mkdirs ();
        }
        if (!file.exists ()) {
            try {
                file.createNewFile ();
            } catch (IOException e) {
            }
        }
        return file;
    }

    private static void process(Template template, File file, Map<String,String> param) {
        try {
            Writer writer = new BufferedWriter (new OutputStreamWriter (new FileOutputStream (file), StandardCharsets.UTF_8));
            template.process (param,writer);
            template.setAutoFlush (true);
//            VfsUtil.markDirtyAndRefresh ();
//            ProgressManager.getInstance ().run (new Task.Modal (null,"", false){
//                @Override
//                public void run(@NotNull ProgressIndicator indicator) {
//
//                }
//            });
        } catch (Exception e) {
        }
    }
}
